package com.action.boot.mongo.mongo_template.controller;

import com.action.boot.mongo.mongo_template.entity.Order;
import com.action.boot.mongo.mongo_template.service.OrderService;
import com.action.boot.mongo.mongo_template.util.Object2DBObject;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Wuxiang on 2017/9/2.
 *
 * 测试 DBObject 进行抽象化处理
 */
@RestController
public class OrdeController {

    @Autowired
    OrderService orderService;

    @RequestMapping(value = "/order",method = RequestMethod.GET)
    public String addOrder() {
        orderService.addOrder();
        System.out.println("保存成功！！！");
        return "保存成功！";
    }

    @RequestMapping(value = "/orders",method = RequestMethod.GET)
    public List<Order> selectAll() {
        System.out.println("查询所有。");
        return orderService.selectAll();
    }


    @RequestMapping(value = "/insert",method = RequestMethod.GET)
    public String json() {
        Map<String, Object> map = new HashMap<>();
        map.put("1", "aaa");
        map.put("2", "bbb");
        map.put("3", "ddd");
        map.put("4", "ccc");
        DBObject bson = Object2DBObject.change(map);
        orderService.json(bson);
        return null;
    }

    @RequestMapping(value = "/find",method = RequestMethod.GET)
    public List<DBObject> find() {
        List<DBObject> objects = orderService.find();
        objects.forEach(System.out::println);
        objects.forEach(dbObject -> {
            dbObject.put("5", "new");
            dbObject.removeField("3");
        });
        objects.forEach(System.out::println);
        objects.forEach(dbObject -> {
            System.out.println(dbObject.get("2") + "  " + dbObject.get("3"));
        });
        return objects;
    }

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String saveOne(@RequestBody Object object) throws Exception {
        System.out.println(object);
        DBObject bson = Object2DBObject.change(object);
        orderService.saveOne(bson);
        return "save success";
    }

    @RequestMapping(value = "/saves",method = RequestMethod.POST)
    public String saveList(@RequestBody List<Object> objects) {
        objects.forEach(System.out::println);
        List<DBObject> dbObjects = new ArrayList<>();
        objects.forEach(object -> dbObjects.add(Object2DBObject.change(object)));
        orderService.saveList(dbObjects);
        return "save List success";
    }

}
